using Godot;
using System;

public partial class DeathComponent : Node2D
{
	[Export]
	HealthComponent healthComponent;
	[Export]
	Sprite2D sprite;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		GetNode<GpuParticles2D>("GPUParticles2D").Texture = sprite.Texture;
		healthComponent.Died += OnDied;
		
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public void OnDied(){
		if(Owner == null || Owner is not Node2D){
			return ;
		}
		Vector2 spawnPosition = (Owner as Node2D).GlobalPosition;
		Node2D entities = GetTree().GetFirstNodeInGroup("entities_layer") as Node2D;
		GetParent().RemoveChild(this);
		entities.AddChild(this);
		GlobalPosition = spawnPosition;
		GetNode<AnimationPlayer>("AnimationPlayer").Play("default");
		GetNode<RandomStreamPlayer2dComponent>("HitRandomAudioPlayerComponent").PlayRandom();

	}
}
